﻿using System;
using Engine;
using Game;
using GameEntitySystem;

using TemplatesDatabase;

public class ComponentSummoneeFollowBehavior : ComponentSummoneeBehavior, IUpdateable
{
    public float m_importance;

    public ComponentSummonee m_summonee;

    public ComponentBody m_lordBody;

    public ComponentCreatureModel m_lordCreatureModel;

    public new StateMachine m_stateMachine = new StateMachine();

    public Game.Random m_random = new Game.Random();

    public float m_detectRangeFactor = 1f;

    public float m_importanceLevel;

    public bool m_isActive;

    public float DistanceFromLord => Vector3.Distance(m_lordCreatureModel.EyePosition, ((ComponentFrame)m_summonee).Position);

    public UpdateOrder UpdateOrder => (UpdateOrder)0;

    public override bool IsActive => true;

    public override float ImportanceLevel => m_importanceLevel;

    public void LoadLord()
    {
        m_summonee = Entity.FindComponent<ComponentSummonee>(true);
        if (m_summonee != null)
        {
            m_summonee.m_behaviors.Add(this);
            m_lordBody = m_summonee.m_lord.Entity.FindComponent<ComponentBody>(true);
            m_lordCreatureModel = m_summonee.m_lord.Entity.FindComponent<ComponentCreatureModel>();
        }
    }

    public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
    {
        base.Load(valuesDictionary, idToEntityMap);
        try
        {
            LoadLord();
        }
        catch (Exception ex)
        {
            Log.Error(ex);
        }
    }

    public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
    {
        base.Save(valuesDictionary, entityToIdMap);
    }

    public void Update(float dt)
    {
        
        Vector3 vectorFromLord = m_summonee.VectorFromLord;
        m_importanceLevel = vectorFromLord.LengthSquared() / m_detectRangeFactor / m_detectRangeFactor;
    }

    public override void UpdateWhenActive(float dt)
    {
       
        m_summonee.m_lord.m_target = null;
        if (DistanceFromLord > 25f)
        {
            Vector3 val = m_random.Vector3(1f);
            val.Y = MathUtils.Abs(val.Y);
            m_summonee.Position = m_lordCreatureModel.EyePosition + val;
        }
        m_summonee.m_velocity = m_summonee.m_flySpeed * MathUtils.Clamp(DistanceFromLord / 2f - 0.5f, 0f, 1f) * Vector3.Normalize(m_summonee.VectorFromLord);
    }
}
